﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RED_NET_Core.DAL;
using RED_NET_Core.Utilty;
using RED_NET_Core.Entity;
using RED_NET_Core.BLL;

namespace RED_NET.ContentPage
{
    public partial class AddPhoto : System.Web.UI.Page
    {
        int VISIT_ID, Album_ID, USER_ID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //检测用户是否登录
                if (Session["USER"] == null)
                {
                    Response.Write("<script>alert('请先登录！');location.href='Index.aspx';</script>");
                }
            }
            VISIT_ID = Int32.Parse(Request.Params["VISIT_ID"].ToString());
            Album_ID = Int32.Parse(Request.Params["Album_ID"].ToString());
        }


        protected void Photo_Button_Click(object sender, EventArgs e)
        {
            string photoName = PhotoName_Text.Text.ToString();
            string photoContent = PhotoComment_Text.Text.ToString();
            int k = Int32.Parse(Safety.IsValidStr(photoName, 50).value.ToString());
            if (k == 10)
            {
                Response.Write("<script>alert('相片名含有非法字符！');</script>");
                return;
            }
            else if (k == 9)
            {
                Response.Write("<script>alert('相片名过长！');</script>");
                return;
            }

            k = Int32.Parse(Safety.IsValidStr(photoContent, 100).value.ToString());
            if (k == 10)
            {
                Response.Write("<script>alert('相片简介含有非法字符！');</script>");
                return;
            }
            else if (k == 9)
            {
                Response.Write("<script>alert('相片简介过长！');</script>");
                return;
            }
            if (this.FileUpload1.FileName.ToString() != "")
            {
                Album_Photo album_photo = new Album_Photo();
                DateTime photoTime = DateTime.Now;
                string photoUrl = "../Image_Css/Image/Photo_Images/";
                string photoUrl2 = "../Image_Css/Image/Photo_Images/Photo_Images_Small/";
                try
                {
                    string fileName = MakeBigOrSmallImage(FileUpload1, photoUrl, 300, 300, photoUrl2, 60, 60);
                    photoUrl += fileName;
                    photoUrl2 += fileName;
                    album_photo.AddPhoto(Album_ID, PhotoName_Text.Text.ToString(),
                        PhotoComment_Text.Text.ToString(), photoTime, photoUrl, photoUrl2,VISIT_ID);
                }
                catch (Exception ex)
                {
                    ErrorInfo_BLL.AddErrorInfo(VISIT_ID, ex.Message, photoTime);
                    Response.Redirect("~/ContentPage/Error/PageError.aspx");
                }
                Response.Write("<script>alert('添加相片成功！');location.href='Photo.aspx?VISIT_ID=" + VISIT_ID + "&Album_ID=" + Album_ID + "';</script>");
            }
            else
            {
                Response.Write("<script>alert('请选择相片！');</script>");
            }
        }

        protected void Reset_Click(object sender, EventArgs e)
        {
            PhotoName_Text.Text = "";
            PhotoComment_Text.Text = "";
        }

        #region[图片压缩函数(有添加缩略图功能）]

        /// <summary>
        /// 可多次利用，增大缩小上传图片函数
        /// </summary>
        /// <param name="upImage">上传控件的ID值</param>
        /// <param name="savePath">图片保存的相对路径</param>
        /// <param name="toHeight">图片最大高度</param>
        /// <param name="toWidth">图片最大宽度</param>
        /// <returns></returns>
        public string MakeBigOrSmallImage(FileUpload upImage, String savePath, int toHeight, int toWidth, String savePath2, int toHeight2, int toWidth2)
        {
            bool IsChange = false;
            String ttFileName = "";//缩略图文件名
            String tFileName = "";//原始文件名
            String FileName = "";//没有扩展名的文件名
            if (upImage.PostedFile != null)
            {
                HttpPostedFile myImageFile = upImage.PostedFile;
                FileName = System.IO.Path.GetFileNameWithoutExtension(myImageFile.FileName);
                int tFileLen = myImageFile.ContentLength;
                if (tFileLen == 0) return "没有选择上传图片";
                String extension = System.IO.Path.GetExtension(myImageFile.FileName).ToLower();
                if (extension != ".jpg" && extension != ".jpge" && extension != ".png" && extension != ".bmp")
                    return "上传图片格式错误";
                byte[] myData = new byte[tFileLen];
                myImageFile.InputStream.Read(myData, 0, tFileLen);
                //检查当前文件名是否已经存在,若存在，在文件名末尾加1、2、3。。
                tFileName = System.IO.Path.GetFileName(myImageFile.FileName);
                int fileNum = 0;
                while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName)))
                {
                    fileNum++;
                    tFileName = FileName +
                        fileNum.ToString() + extension;
                }
                //保存图片
                System.IO.FileStream newFile = new System.IO.FileStream(
                    System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName),
                    System.IO.FileMode.Create, System.IO.FileAccess.Write);
                newFile.Write(myData, 0, tFileLen);
                newFile.Close();

                //保存缩略图图片
                System.IO.FileStream newFile2 = new System.IO.FileStream(
                    System.Web.HttpContext.Current.Server.MapPath(savePath2 + tFileName),
                    System.IO.FileMode.Create, System.IO.FileAccess.Write);
                newFile2.Write(myData, 0, tFileLen);
                newFile2.Close();
                ttFileName = tFileName;

                //如果图片长宽有任意一个比规定的大，那么压缩图
                try
                {
                    using (System.Drawing.Image sourceImage =
                       System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName)))
                    {
                        //原图高度
                        int oldHeight = sourceImage.Height;
                        int oldWidth = sourceImage.Width;
                        int nowHeight;
                        int nowWidth;
                        if (oldHeight > toHeight || oldWidth > toWidth)
                        {
                            if ((decimal)oldHeight / oldWidth <= (decimal)toHeight / toWidth)
                            {
                                nowHeight = toHeight;
                                nowWidth = toHeight * oldWidth / oldHeight;
                            }
                            else
                            {
                                nowWidth = toWidth;
                                nowHeight = toWidth * oldHeight / oldWidth;
                            }
                            //存好缩略图存放的绝对物理地址
                            ttFileName = "t" + FileName + extension; //小图片名前加个t，防止操作过程因覆盖原图导致程序错误
                            int tfileNum = 0;
                            while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(savePath + ttFileName)))
                            {
                                tfileNum++;
                                ttFileName = "t" + FileName + tfileNum.ToString() + extension;
                            }
                            String smallImageSavePath =
                                System.Web.HttpContext.Current.Server.MapPath(savePath + ttFileName);
                            //以等比例压缩绘制缩略图
                            using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(nowWidth, nowHeight))
                            {
                                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                                {
                                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    g.Clear(System.Drawing.Color.Black);
                                    g.DrawImage(sourceImage, new System.Drawing.Rectangle(0, 0, nowWidth, nowHeight),
                                        new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight),
                                        System.Drawing.GraphicsUnit.Pixel);
                                    bitmap.Save(smallImageSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                            IsChange = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //记录错误信息
                    Users user = (Users)Session["USER"];
                    int User_Id = user.UserId;
                    DateTime time = DateTime.Now;
                    ErrorInfo_BLL.AddErrorInfo(User_Id, ex.Message, time);
                    Response.Redirect("~/ContentPage/Error/PageError.aspx");
                    //压缩过程出错也视为有压缩，删除大图
                    IsChange = true;
                    throw ex;
                }
                //如果图片有压缩，那么删除大图
                if (IsChange) System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName));

                //处理缩略图
                //处理缩略图有图片到指定大小
                try
                {
                    using (System.Drawing.Image sourceImage =
                       System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(savePath2 + tFileName)))
                    {
                        //原图高度
                        int oldHeight = sourceImage.Height;
                        int oldWidth = sourceImage.Width;
                        int nowHeight;
                        int nowWidth;
                        if (oldHeight > toHeight || oldWidth > toWidth)
                        {
                            if ((decimal)oldHeight / oldWidth <= (decimal)toHeight2 / toWidth2)
                            {
                                nowHeight = toHeight2;
                                nowWidth = toHeight2 * oldWidth / oldHeight;
                            }
                            else
                            {
                                nowWidth = toWidth2;
                                nowHeight = toWidth2 * oldHeight / oldWidth;
                            }
                            //存好缩略图存放的绝对物理地址
                            String smallImageSavePath =
                                System.Web.HttpContext.Current.Server.MapPath(savePath2 + ttFileName);
                            //以等比例压缩绘制缩略图
                            using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(nowWidth, nowHeight))
                            {
                                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                                {
                                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    g.Clear(System.Drawing.Color.Black);
                                    g.DrawImage(sourceImage, new System.Drawing.Rectangle(0, 0, nowWidth, nowHeight),
                                        new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight),
                                        System.Drawing.GraphicsUnit.Pixel);
                                    bitmap.Save(smallImageSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                            IsChange = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //记录错误信息
                    Users user = (Users)Session["USER"];
                    int User_Id = user.UserId;
                    DateTime time = DateTime.Now;
                    ErrorInfo_BLL.AddErrorInfo(User_Id, ex.Message, time);
                    Response.Redirect("~/ContentPage/Error/PageError.aspx");
                    //压缩过程出错也视为有压缩，删除大图
                    IsChange = true;
                    throw ex;
                }
                //如果图片有压缩，那么删除大图
                if (IsChange) System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(savePath2 + tFileName));
            }
            return ttFileName;
        }
    }
        #endregion
}
